package top.lidee.utils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class DistinctUtil {
    private static final String API_KEY = "你的高德key";
    private static final String BASE_URL = "https://restapi.amap.com/v3/direction/driving";

    /**
     * 根据地址获取经纬度
     *
     * @param addr 地址
     * @return
     */
    public static Map<String, Object> getLatAndLngByAddress(String addr) {
        String address = "";
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // key如果失效了就去高德地图官网申请
        String url = "https://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + "4d57813b7b9157d66899cc4c1f22dc04";

        URL myURL = null;
        URLConnection httpsConn;
        // 进行转码
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            // empty
        }
        StringBuffer sb = new StringBuffer();
        try {
            httpsConn = myURL.openConnection();
            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                while ((data = br.readLine()) != null) {
                    sb.append(data);
                }
                insr.close();
            }
        } catch (IOException e) {

        }

        Map<String, Object> map = new HashMap<>();
        JSONObject resultJson = JSON.parseObject(sb.toString());
        JSONArray geocodes = resultJson.getJSONArray("geocodes");


        String lat = "";
        String lng = "";

        if (geocodes != null) {
            JSONObject jsonObject = geocodes.getJSONObject(0);
            String location = jsonObject.getString("location");

            if (org.apache.commons.lang.StringUtils.isNotEmpty(location)) {
                String latAndLng[] = location.split(",");
                if (latAndLng.length == 2) {
                    lat = latAndLng[1];
                    lng = latAndLng[0];
                }
            }
        }

        map.put("lat", lat);
        map.put("lng", lng);

        return map;
    }

    public static void main(String[] args) {
        Map<String, Object> map = getLatAndLngByAddress("合肥市包河区SCC凤凰写字楼");
        System.out.println(map);
    }


    public static String getDistance(String origin, String destination) throws Exception {
//        String origin = "106.6240283203125,29.656462944878474";
//        String destination = "107.51576,26.305805";
        System.out.println("接搜的经纬度"+origin+"目的地"+destination);
        String url = BASE_URL + "?key=" + API_KEY +
                "&origin=" + origin +
                "&destination=" + destination +
                "&output=json";

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        connection.disconnect();

        // 使用Fastjson解析JSON字符串
        JSONObject jsonResponse = JSONObject.parseObject(response.toString());

        // 获取路径信息并提取距离
        JSONObject routes = jsonResponse.getJSONObject("route");
        JSONArray path = routes.getJSONArray("paths");
        JSONObject jsonObject = path.getJSONObject(0);
        String distance = jsonObject.get("distance").toString();
        double number = Double.parseDouble(distance) / 1000;
        System.out.println("距离：" + number + "公里");
        return Double.toString(number);
    }
 
}
 